package com.ruoyi.his.service.impl;

import java.util.List;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.ruoyi.his.domain.Doctor;
import com.ruoyi.his.mapper.DepartmentMapper;
import com.ruoyi.his.mapper.DoctorMapper;
import com.ruoyi.his.domain.Department;
import com.ruoyi.his.service.IDepartmentService;

/**
 * 科室信息Service业务层处理
 */
@Service
public class DepartmentServiceImpl implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;

    @Autowired
    private DoctorMapper doctorMapper;

    @Override
    public Department selectDepartmentById(Long id) {
        Department department = departmentMapper.selectDepartmentById(id);
        if (department != null) {
            // 查询关联的医生列表
            List<Doctor> doctors = doctorMapper.selectDoctorListByDeptId(id);
            department.setDoctorList(doctors);
        }
        return department;
    }
    // 添加根据科室ID查询医生列表的方法

    @Override
    public List<Department> selectDepartmentList(Department department) {
        return departmentMapper.selectDepartmentList(department);
    }

    @Transactional
    @Override
    public int insertDepartment(Department department) {
        // 1. 插入科室信息
        department.setCreateTime(DateUtils.getNowDate());
        int rows = departmentMapper.insertDepartment(department);

        // 2. 插入科室-医生关联关系
        if (department.getDoctorIds() != null && !department.getDoctorIds().isEmpty()) {
            departmentMapper.batchInsertRel(department);
        }
        return rows;
    }

    @Transactional
    @Override
    public int updateDepartment(Department department) {
        // 1. 更新科室信息
        department.setUpdateTime(DateUtils.getNowDate());
        int rows = departmentMapper.updateDepartment(department);

        // 2. 先删除旧的关联关系
        departmentMapper.deleteRelByDeptId(department.getId());

        // 3. 插入新的关联关系
        if (department.getDoctorIds() != null && !department.getDoctorIds().isEmpty()) {
            departmentMapper.batchInsertRel(department);
        }
        return rows;
    }

    @Transactional
    @Override
    public int deleteDepartmentByIds(Long[] ids) {
        // 1. 删除科室-医生关联关系
        for (Long id : ids) {
            departmentMapper.deleteRelByDeptId(id);
        }

        // 2. 删除科室
        return departmentMapper.deleteDepartmentByIds(ids);
    }

    @Transactional
    @Override
    public int deleteDepartmentById(Long id) {
        // 1. 删除科室-医生关联关系
        departmentMapper.deleteRelByDeptId(id);

        // 2. 删除科室
        return departmentMapper.deleteDepartmentById(id);
    }
}